package com.neusoft.neuiotms.dcam.fixed.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.bean.TreeBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.bizcore.web.utils.EasyPoiExcelUtil;
import com.neusoft.bizcore.web.utils.EasyPoiStylerColorImpl;
import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.neuiotms.common.constant.AHConstants;
import com.neusoft.neuiotms.dcam.common.model.Location;
import com.neusoft.neuiotms.dcam.common.service.LocationService;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.converter.AssetConverter;
import com.neusoft.neuiotms.dcam.fixed.converter.InventoryDutyConverter;
import com.neusoft.neuiotms.dcam.fixed.converter.InventoryResultConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.InventoryDutyDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.InventoryDutyHistoryDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.InventoryResultDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.model.AssetType;
import com.neusoft.neuiotms.dcam.fixed.model.InventoryDuty;
import com.neusoft.neuiotms.dcam.fixed.model.InventoryPlan;
import com.neusoft.neuiotms.dcam.fixed.model.InventoryResult;
import com.neusoft.neuiotms.dcam.fixed.model.enums.InventoryDutyStatus;
import com.neusoft.neuiotms.dcam.fixed.model.enums.InventoryPlanStatus;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.ConnectionRelationRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.InventoryDutyRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.InventoryPlanRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.InventoryResultRepository;
import com.neusoft.neuiotms.dcam.fixed.service.InventoryDutyHistoryService;
import com.neusoft.neuiotms.dcam.fixed.service.InventoryDutyService;
import com.neusoft.neuiotms.dcam.fixed.service.InventoryResultService;
import com.neusoft.neuiotms.dcam.fixed.vo.InventoryResultVO;
import com.neusoft.neuiotms.micro.auth.AuthMicroService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class InventoryDutyServiceImpl implements InventoryDutyService {

    @Autowired
    private InventoryDutyRepository inventoryDutyRepository;
    @Autowired
    private InventoryDutyConverter inventoryDutyConverter;
    @Autowired
    private InventoryPlanRepository inventoryPlanRepository;
    @Autowired
    private ConnectionRelationRepository relationRepository;
    @Autowired
    private InventoryResultConverter inventoryResultConverter;
    @Autowired
    private AuthMicroService authMicroService;
    @Autowired
    private InventoryResultRepository inventoryResultRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetConverter assetConverter;
    @Autowired
    private InventoryResultService inventoryResultService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private InventoryDutyHistoryService inventoryDutyHistoryService;

    @Override
    public List<InventoryDutyDTO> findAll(final Searchable searchable) {
        final List<InventoryDuty> models = this.inventoryDutyRepository.search(searchable);
        return this.inventoryDutyConverter.toListDTO(models);
    }

    @Override
    public Page<InventoryDutyDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<InventoryDuty> models = this.inventoryDutyRepository.search(pageable, searchable);
        return this.inventoryDutyConverter.toPageDTO(models);
    }

    @Transactional
    @Override
    public void create(final InventoryDutyDTO dto) {

        InventoryPlan inventoryPlan = null;
        try {
            inventoryPlan = this.inventoryPlanRepository.getOne(dto.getInventoryPlanId());
        } catch (final Exception e) {
            throw new UnitedException("盘点计划不存在");
        }

        // 如果已经下发的计划不能新建任务
        if (!InventoryPlanStatus.created.equals(inventoryPlan.getStatus())) {
            throw new UnitedException("计划已经下发,不能新建任务!");
        }

        // 按部门下发盘点任务，会按部门拆分生成多个任务
        // 暂时只支持一个任务关联一个部门
        if (dto.getOrgCodes().size() == 0) {
            throw new UnitedException("至少选择一个部门");
        }
        if (dto.getOrgCodes().size() > 1) {
            throw new UnitedException("只支持一个任务关联一个部门");
        }
        // 盘点部门编码
        final String orgCode = dto.getOrgCodes().get(0);

        InventoryDuty inventoryDuty = this.inventoryDutyConverter.toModel(dto);
        inventoryDuty.setInventoryPlan(inventoryPlan);

        if (inventoryDuty.getOrgRelation().size() > 0) {
            // 保存实体
            this.relationRepository.saveAll(inventoryDuty.getOrgRelation());
        }

        inventoryDuty = this.inventoryDutyRepository.save(inventoryDuty);

        // 查询管理资产条件
        final Searchable queryAssets = new Searchable();
        queryAssets.put("managementOrgCode", orgCode);
        if (dto.getAssetTypeCodes().size() > 0) {
            queryAssets.put("typeCodesArr", dto.getAssetTypeCodes());
        }
        if (dto.getLocationCodes().size() > 0) {
            queryAssets.put("locationArr", dto.getLocationCodes());
        }
        final List<Asset> assets = this.assetRepository.search(queryAssets);

        final List<AssetDTO> dtoArr = this.assetConverter.toListDTO(assets);
        for (final AssetDTO k : dtoArr) {
            final InventoryResultDTO r = this.inventoryResultConverter.toDTO(k, inventoryDuty.getId());
            // 下发资产
            this.inventoryResultService.create(r);
        }
    }

    @Override
    public InventoryDutyDTO details(final Long id) {

        final InventoryDuty model;
        try {
            model = this.inventoryDutyRepository.getOne(id);
        } catch (final Exception e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }
        return this.inventoryDutyConverter.toDTO(model, false);
    }

    @Override
    public void delete(final Long id) {
        InventoryDuty model;
        try {
            model = this.inventoryDutyRepository.getOne(id);
        } catch (final Exception e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        final InventoryPlan planModel = model.getInventoryPlan();

        if (planModel != null) {
            // 如果已经下发的计划不能删除任务
            if (!InventoryPlanStatus.created.equals(planModel.getStatus())) {
                throw new UnitedException("计划已经下发,不能删除任务!", new Object[] {});
            }
        }

        // 组织
        model.getOrgRelation().forEach(m -> {
            this.relationRepository.deleteById(m.getId());
        });
        model.getOrgRelation().clear();

        // 删除任务
        this.inventoryDutyRepository.deleteById(id);
    }

    @Override
    public InventoryDutyDTO update(final Long id, final InventoryDutyDTO dto) {

        final String orgCode = dto.getOrgCodes().get(0);
        InventoryDuty inventoryDuty;
        try {
            inventoryDuty = this.inventoryDutyRepository.getOne(id);
        } catch (final Exception e) {
            throw new UnitedException("盘点任务不存在");
        }

        // 检查下部门是否变了，如果变了，得重新生成任务结果项
        boolean orgChanged = false;
        if (!orgCode.equals(inventoryDuty.getOrgRelation().get(0).getBusinessId())) {
            orgChanged = true;
        }
        // 检查下位置是否变了，如果变了，得重新生成任务结果项
        boolean locationChanged = false;
        if (inventoryDuty.getLocations().size() != dto.getLocationCodes().size()) {
            locationChanged = true;
        } else {
            boolean eq = true;
            for (final Location l : inventoryDuty.getLocations()) {
                if (!dto.getLocationCodes().contains(l.getCode())) {
                    eq = false;
                    break;
                }
            }
            locationChanged = !eq;
        }

        // 检查下位置是否变了，如果变了，得重新生成任务结果项
        boolean assetTypeChanged = false;
        if (inventoryDuty.getAssetTypes().size() != dto.getAssetTypeCodes().size()) {
            assetTypeChanged = true;
        } else {
            boolean eq = true;
            for (final AssetType a : inventoryDuty.getAssetTypes()) {
                if (!dto.getAssetTypeCodes().contains(a.getCode())) {
                    eq = false;
                    break;
                }
            }
            assetTypeChanged = !eq;
        }

        dto.setId(inventoryDuty.getId());
        inventoryDuty = this.inventoryDutyConverter.toModel(dto);
        inventoryDuty = this.inventoryDutyRepository.save(inventoryDuty);

        if (orgChanged || locationChanged || assetTypeChanged) {
            inventoryDuty.getDutyResults().clear();
            this.inventoryResultService.clearResults(inventoryDuty.getId());

            final Searchable queryAssets = new Searchable();
            queryAssets.put("managementOrgCode", orgCode);
            if (dto.getAssetTypeCodes().size() > 0) {
                queryAssets.put("typeCodesArr", dto.getAssetTypeCodes());
            }
            if (dto.getLocationCodes().size() > 0) {
                queryAssets.put("locationArr", dto.getLocationCodes());
            }
            final List<Asset> assets = this.assetRepository.search(queryAssets);

            final List<AssetDTO> dtoArr = this.assetConverter.toListDTO(assets);
            for (final AssetDTO k : dtoArr) {
                final InventoryResultDTO r = this.inventoryResultConverter.toDTO(k, inventoryDuty.getId());
                // 下发资产
                this.inventoryResultService.create(r);
            }
        }

        return this.inventoryDutyConverter.toDTO(inventoryDuty);
    }

    @Override
    @Transactional
    public void enable(final Long id, final String status) {

        InventoryDuty model;
        try {
            model = this.inventoryDutyRepository.getOne(id);
        } catch (final Exception e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        final InventoryPlan planModel = model.getInventoryPlan();

        if (planModel != null) {
            // 计划下发了才能确认任务
            if (!InventoryPlanStatus.issued.equals(planModel.getStatus())) {
                throw new UnitedException("只有下发的计划才能确认!", new Object[] {});
            }
        }

        if (status.equals("finish")) {
            model.setStatus(InventoryDutyStatus.finish);

            this.inventoryDutyHistoryService.create(InventoryDutyHistoryDTO.builder().dutyCode(model.getCode())
                    .comment("盘点责任人提交任务").status(1).createTime(Calendar.getInstance().getTime()).build());

        }

        if (status.equals("doing")) {
            model.setStatus(InventoryDutyStatus.doing);
        }

        this.inventoryDutyRepository.save(model);
    }

    @Override
    public Workbook download(final Long id) {

        InventoryDuty model;
        try {
            final Optional<InventoryDuty> opt = this.inventoryDutyRepository.findById(id); //getOne(id);
            model = opt.get();
        } catch (final Exception e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        final List<InventoryResultVO> vos =
                new ArrayList<>();

        if ((model != null) && CollectionUtils.isNotEmpty(model.getDutyResults())) {
            model.setDutyResults(model.getDutyResults().subList(0, model.getDutyResults().size()));
        }

        model.getDutyResults().stream().map(m -> {
            return this.inventoryResultConverter.toVO(m);
        }).filter(ele -> null != ele).forEach(vos::add);

        final ExportParams param = new ExportParams("盘点资产明细", "资产详细", ExcelType.XSSF);
        param.setStyle(EasyPoiStylerColorImpl.class);
        final Workbook workbook = ExcelExportUtil.exportExcel(param, InventoryResultVO.class, vos);

        final InventoryPlan inventoryPlan = model.getInventoryPlan();

        this.setOrgUserCascade(workbook, inventoryPlan.getBelongs());
        // 设置位置和状态的约束数据
        final List<Map<String, Object>> constraint = this.setConstraint(inventoryPlan.getBelongs());
        EasyPoiExcelUtil.setConstraint(constraint, workbook, DCAMConsts.ASSET_START_CONSTRAINT_ROW,
                DCAMConsts.ASSET_CONSTRAINT_ROW);
        return workbook;
    }

    /**
     * 上传盘点信息
     */
    @Override
    public String upload(final MultipartFile file, final Long id) {
        final StringBuilder errorMsg = new StringBuilder();
        final ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerify(true);
        try {
            final ExcelImportResult<InventoryResultVO> result =
                    ExcelImportUtil.importExcelMore(file.getInputStream(), InventoryResultVO.class, params);
            if (result.isVerifyFail()) {
                final List<InventoryResultVO> failList = result.getFailList();
                failList.forEach(l -> {
                    errorMsg.append("第" + (l.getRowNum() + 1) + "行," + l.getErrorMsg() + "! \n");
                });

            }

            final List<InventoryResult> models = new ArrayList<>();
            final List<InventoryResultVO> saveList = result.getList();

            for (final InventoryResultVO inventory : saveList) {
                if (StringUtils.isNotEmpty(inventory.getCode())) {
                    InventoryResult oldModel = null;

                    final List<InventoryResult> oldModelList =
                            this.inventoryResultRepository.getByDutyIdAndCode(id, inventory.getCode());

                    if (CollectionUtils.isNotEmpty(oldModelList)) {
                        oldModel = oldModelList.get(0);
                    }

                    if (oldModel != null) {
                        this.updateInventoryResult(models, inventory, oldModel);
                    } else {
                        this.inventoryProfit(id, models, inventory);
                    }
                }
            }

            if (!models.isEmpty()) {
                this.inventoryResultRepository.saveAll(models);
            }

        } catch (final Exception e) {
            e.printStackTrace();
            InventoryDutyServiceImpl.log.error("上传失败", e);
            throw new UnitedException(e.getMessage(), new Object[] {});
        }

        return errorMsg.toString();
    }

    // 更新盘点信息
    private void updateInventoryResult(final List<InventoryResult> models, final InventoryResultVO inventory,
            final InventoryResult oldModel) {
        // 存在子更新，变更的位置、使用人、部门

        final ResultListDTO<Map<String, Object>> allUsers = this.authMicroService.allUsers();

        if (StringUtils.isNotEmpty(inventory.getUpdateUserName())) {
            final Optional<Map<String, Object>> userMap = allUsers.getData().stream()
                    .filter(it -> inventory.getUpdateUserName().equals((it.get("name")))).findFirst();
            if (userMap.isPresent()) {
                oldModel.setUpdateUserId((String) userMap.get().get("username"));
                oldModel.setUpdateUserName((String) userMap.get().get("name"));
            }
        }

        if (StringUtils.isNotEmpty(inventory.getUpdateOrgName())) {
            final ResultListDTO<Map<String, Object>> orgs = this.authMicroService.orgIndex();
            final List<String> orgCode =
                    orgs.getData()
                            .stream()
                            .filter(e -> e.get("name").equals(inventory.getUpdateOrgName()))
                            .map(e -> e.get("code").toString())
                            .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orgCode)) {
                oldModel.setUpdateOrgCode(orgCode.get(0));
                oldModel.setUpdateOrgName(inventory.getUpdateOrgName());
            }
        }

        if (StringUtils.isNotEmpty(inventory.getUpdateLocationName())) {
            final int idx = inventory.getUpdateLocationName().indexOf("_");
            if (idx > -1) {
                final String locationName = inventory.getUpdateLocationName().substring(0, idx);
                final String locationCode = inventory.getUpdateLocationName().substring(idx + 1,
                        inventory.getUpdateLocationName().length());

                if (StringUtils.isNotEmpty(locationName) && StringUtils.isNotEmpty(locationCode)) {
                    oldModel.setUpdateLocationCode(locationCode);
                    oldModel.setUpdateLocationName(locationName);
                }
            }
        }

        oldModel.setDutyResultStatus(inventory.getResultStatus());

        models.add(oldModel);
    }

    // 添加盘盈
    private void inventoryProfit(final Long id, final List<InventoryResult> models,
            final InventoryResultVO inventory) {
        final InventoryDuty inventoryDuty = this.inventoryDutyRepository.getOne(id);
        final InventoryResult model = this.inventoryResultConverter.toModel(inventory);

        //类型
        //        if (!StringUtils.isEmpty(inventory.getAssetTypeName())) {
        //            try {
        //                final AssetType type =
        //                        this.assetTypeRepository.findByName(inventory.getAssetTypeName());
        //                model.setType(type);
        //            } catch (final EntityNotFoundException e) {
        //                throw new UnitedException("资产类型不存在", new Object[] {inventory.getAssetTypeName() });
        //            }
        //        }
        //位置
        // TODO
        //        if (!StringUtils.isEmpty(inventory.getLocationName())) {
        //            try {
        //                final Location location =
        //                        this.locationRepository.findByName(inventory.getLocationName());
        //                model.setLocation(location);
        //            } catch (final EntityNotFoundException e) {
        //                throw new UnitedException("资产类型不存在", new Object[] {inventory.getLocationName() });
        //            }
        //        }

        // 使用人
        if (!StringUtils.isEmpty(inventory.getUserName())) {
            final UserBean userBean =
                    this.authMicroService.loadUserByUsername(inventory.getUserName()).getData();
            model.setUserName(inventory.getUserName());
            if (userBean != null) {
                model.setUserId(String.valueOf(userBean.getUserId()));
            }
        }

        // 部门
        if (!StringUtils.isEmpty(inventory.getOrgName())) {
            final ResultListDTO<Map<String, Object>> orgs = this.authMicroService.orgIndex();
            final List<String> orgCode =
                    orgs.getData()
                            .stream()
                            .filter(e -> e.get("name").equals(inventory.getOrgName()))
                            .map(e -> e.get("id").toString())
                            .collect(Collectors.toList());
            model.setOrgName(inventory.getOrgName());
            if (CollectionUtils.isNotEmpty(orgCode)) {
                model.setOrgId(orgCode.get(0));
            }
        }

        if (inventoryDuty != null) {
            model.setInventoryDuty(inventoryDuty);
            model.setDutyResultStatus(inventory.getResultStatus());
            models.add(model);
        }
    }

    @SuppressWarnings("unchecked")
    private void setOrgUserCascade(final Workbook workbook, final String belongs) {

        final ResultListDTO<Map<String, Object>> resultOfOrg = this.authMicroService.allOrganizations();
        final List<Map<String, Object>> orgList = resultOfOrg.getData();
        final List<Map<String, Object>> belongsOrgList;
        if (AHConstants.BELONG_KJ_CODE.equals(belongs)) {
            belongsOrgList = orgList.stream()
                    .filter(it -> String.valueOf(it.get("code")).startsWith(AHConstants.BELONG_KJ_CODE))
                    .collect(Collectors.toList());
        } else {
            belongsOrgList = orgList.stream()
                    .filter(it -> !(String.valueOf(it.get("code")).startsWith(AHConstants.BELONG_KJ_CODE))
                            || String.valueOf(it.get("code")).equals("kj"))
                    .collect(Collectors.toList());
        }

        final List<String> allParent = new ArrayList<>();
        final List<String> mainParent = new ArrayList<>();
        final Map<String, List<String>> cascadeMap = new HashMap<>();

        belongsOrgList.forEach(t -> {
            final String value = t.get("name") + "";
            mainParent.add(value);
            allParent.add(value);
            final List<String> children = new ArrayList<>();

            final ResultDTO<Map<String, Object>> orgResult =
                    this.authMicroService.orgInfoByCode(String.valueOf(t.get("code")));
            final Map<String, Object> orgInfo = orgResult.getData();
            final List<Map<String, Object>> users = (List<Map<String, Object>>) orgInfo.get("users");
            users.stream().map(it -> String.valueOf(it.get("name"))).forEach(children::add);
            cascadeMap.put(value, children);
        });

        // 使用部门属性的列号
        final int col1 = 6;
        // 使用人属性的列号
        final int col2 = 7;
        final ArrayList<Integer> columns =
                Lists.newArrayList(col1, col2);

        EasyPoiExcelUtil.cascade(workbook, mainParent, allParent, cascadeMap, columns, 0,
                1,
                DCAMConsts.ASSET_CONSTRAINT_ROW);

    }

    /**
     * 设置位置和状态的约束数据
     *
     * @param belongs
     * @return
     */
    private List<Map<String, Object>> setConstraint(final String belongs) {
        final List<Map<String, Object>> constraint = new ArrayList<>();

        final int[] constraintColumns = new int[] {5, 8 };

        for (final int element : constraintColumns) {
            final List<String> constraintList = new ArrayList<>();
            switch (element) {
            case 8:
                final List<TreeBean> locTree = this.locationService.tree(belongs);
                for (final TreeBean b : locTree) {
                    constraintList.add(b.getTitle() + DCAMConsts.DICTIONARY_SPLITOR + b.getCode());
                    this.joinLocationTree(constraintList, b, b.getTitle());
                }
                break;
            case 5:
                constraintList.add("待盘");
                constraintList.add("盘平");
                constraintList.add("盘亏");
                break;
            default:
                break;
            }
            if (!constraintList.isEmpty()) {
                final Map<String, Object> map = new HashMap<>();
                map.put("list", constraintList);
                map.put("col", element);
                constraint.add(map);
            }
        }
        return constraint;
    }

    /**
     * 将位置树，生成A-B-C_C编码，格式的结构，这样的话，在下载模板中，位置列可以把所有位置都显示出来
     *
     * @param results
     * @param parent
     * @param parentPrefix
     */
    private void joinLocationTree(final List<String> results, final TreeBean parent, final String parentPrefix) {
        if (parent.getChildren().size() > 0) {
            for (final TreeBean b : parent.getChildren()) {
                final String tmp = parentPrefix + "-" + b.getTitle() + DCAMConsts.DICTIONARY_SPLITOR + b.getCode();
                results.add(tmp);
                this.joinLocationTree(results, b, parentPrefix + "-" + b.getTitle());
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public String uploadPd(final MultipartFile file) {
        String json;
        try {
            json = new String(file.getBytes());
        } catch (final IOException e) {
            return "解析文件失败";
        }

        final Map<String, Object> map = JsonUtils.jsonToMap(json);
        final List<Map<String, Object>> tasks = (List<Map<String, Object>>) map.get("data");

        final Map<Long, Map<String, Object>> cachedResult = new HashMap<>();
        for (final Map<String, Object> task : tasks) {
            final List<Map<String, Object>> results = (List<Map<String, Object>>) task.get("dutyResults");
            for (final Map<String, Object> result : results) {
                cachedResult.put(Long.valueOf(String.valueOf(result.get("id"))), result);
            }
        }

        if (cachedResult.isEmpty()) {
            return "盘点结果项不能为空";
        }

        this.inventoryResultService.updatePan(cachedResult);

        return "";
    }

    @Override
    @Transactional
    public void reject(Long id, String reason) {
        final InventoryDuty model = this.inventoryDutyRepository.findById(id).orElse(null);
        if (null != model) {
            model.setStatus(InventoryDutyStatus.doing);
            this.inventoryDutyRepository.save(model);
            this.inventoryDutyHistoryService.create(InventoryDutyHistoryDTO.builder().dutyCode(model.getCode())
                    .comment(reason).status(2).createTime(Calendar.getInstance().getTime()).build());

        }

    }

}
